package com.jack.common.dubbo.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Activate(
        group = {"consumer", "provider"},
        value = {"validation"},
        order = 10000
)
@Slf4j
public class ArgValidatorFilter implements Filter {


    @SneakyThrows
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
        Object[] args = invocation.getArguments();
        if (args != null && args.length != 0) {
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < args.length; i++) {
                Annotation[] parameterAnnotation = parameterAnnotations[i];
                try {
                    ValidationUtils.validate(args[i]);
                } catch (RuntimeException e) {
                    return AsyncRpcResult.newDefaultAsyncResult(e, invocation);
                }
            }
        }
        return invoker.invoke(invocation);
    }
}
